package com.hebeiboruan.user.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.hebeiboruan.common.exception.CommonException;
import com.hebeiboruan.common.exception.ServiceResultEnum;
import com.hebeiboruan.entity.system.User;
import com.hebeiboruan.user.service.UserService;
import org.springframework.beans.factory.annotation.Value;


import java.util.ArrayList;

public class UserListener implements ReadListener<User> {
    @Value("${project.batchCount}")
    private static  int BATCH_COUNT;
    private ArrayList<User> list=new ArrayList<>(BATCH_COUNT);
    private UserService userService;

    public UserListener(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void invoke(User user, AnalysisContext analysisContext) {
        list.add(user);
        if(list.size()>BATCH_COUNT){
            save();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        save();
    }
    private void save(){
        try{
            userService.saveBatch(list);
            list= ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }catch (Exception e){
            throw new CommonException(ServiceResultEnum.BATCH_INSERT_ERROR,e);
        }

    }
}
